package com.htudata.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.htudata.common.enums.A2CodeEnum;
import com.htudata.core.util.ResultGenerator;
import com.htudata.core.util.operation.HttpOperationUtils;
import com.htudata.core.util.operation.UrlOperationUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TokenService {

  
  public String validateToken(String a2, String a2InfoUrl) throws Exception {
    String url = a2InfoUrl.replace("{a2}", URLEncoder.encode(a2, "UTF-8"));
    return HttpOperationUtils.sendGet(UrlOperationUtils.getUrlWithoutParam(url),
            UrlOperationUtils.getUrlParamFromUrl(url), "UTF-8");
  }
  
  public String validateToken(HttpServletRequest request, HttpServletResponse response, String tokenJson) throws Exception{
    try {
      JSONObject root = JSON.parseObject(tokenJson);
      if (root != null && root.getJSONObject("data").getIntValue("result") == 1) {
        if (request != null)
          request.setAttribute("a2Info", root.getJSONObject("data").getString("a2Info")); 
        return root.getJSONObject("data").getString("a2Info");
      }
      else{
        if (response != null) {
          response.setStatus(403);
          writeResultWithA2Status(response);
        }
        return null;
      }
    } catch (Exception e) {
      if (response != null) {
        response.setStatus(403);
        writeResultWithA2Status(response);
      }
      throw e;
    }

  }
  
  public void writeResultWithA2Status(HttpServletResponse response) throws Exception {
    JSONObject resultWithA2Status = ResultGenerator.genResultWithA2Status(ResultGenerator.genResult("0", null),
            A2CodeEnum.code_0.getCode());
    PrintWriter out = response.getWriter();
    IOUtils.write(resultWithA2Status.toJSONString(), out);
    IOUtils.closeQuietly(out);
  }
  
  public static long getUserId(HttpServletRequest request) throws Exception  {
    long result = -1L;
    if (request == null)
      return result;
    result = getUserId((String)request.getAttribute("a2Info"));
    return result;
  }
  
  public static long getUserId(String a2Info)   {
    long result = -1L;
    result = JSONArray.parseObject(a2Info).getLongValue("userId");
    return result;
  }
  
  public static long getRoleType(HttpServletRequest request) {
    long result = -1L;
    if (request == null)
      return result;
    result = getRoleType((String)request.getAttribute("a2Info"));
    return result;
  }
  
  public static long getRoleType(String a2Info) {
    long result = -1L;
    result = JSONArray.parseObject(a2Info).getLongValue("roleType");
    return result;
  }
}
